const path = require('path')
const EJS = require('ejs')
const DB = require('./DB.js');
const Utils = require('lsd-utils');
const fs = require('fs');

function renderClass(tpl,tabal) {

    let fields = [];

    // console.log(Utils.ucfirst)
    let data = {
        TABLE_NAME: tabal[0].TABLE_NAME,
        ucfirst: Utils.ucfirst,
        tabal: tabal
    };
    return EJS.render(tpl, data);
}

function writeClass(_path, data) {
    // console.log('_path')
    // console.log(_path)
    fs.writeFileSync(_path, data);
}
async function createModel(opt) {
    let config = Object.assign({},{
        tpl:`${__dirname}/db_model.ejs`,
        dbName: "permis",
        assetsRoot:path.resolve('model/')
    },opt)
    const tpl = fs.readFileSync(config.tpl, 'utf-8');
// console.log('config.assetsRoot')
// console.log(config.assetsRoot)
    let db = new DB();

    db.debug = true;
    // db.open();
    let tables = await db
        .query('show tables')
        .end();
    console.log('tables')
    console.log(tables)
        // return;
    for (let v in tables) {
        let tabalName = tables[v][`Tables_in_${config.dbName}`];
        console.log(tabalName)
        let tabal = await db.query(`SELECT
        *
        FROM
        information_schema.COLUMNS`)
            .where(`TABLE_NAME = '${tabalName}'`)
            .where(`TABLE_SCHEMA = '${config.dbName}'`)
            // .where(`TABLE_NAME = '${tabalName}'`)
            .end();
        // let data = {};
        let _path = config.assetsRoot+'\\'+Utils.ucfirst(tabalName)+'.js';
        // console.log()
        writeClass(_path, renderClass(tpl,tabal))

    }
    // db.close();
    // fs.close();
}
// createModel();
module.exports = createModel;